package com.playball.lottery.frm.kjinfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.R.integer;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.JddMainActivity;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.PullDownView;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.customview.PullDownView.OnPullDownListener;
import com.playball.lottery.frm.buyhall.JcBasketballActivity;
import com.playball.lottery.nt.orjdd.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.DateUtil;
import com.playball.lottery.util.KaiJiangUtil;
import com.playball.lottery.util.SysApplication;


/**
 * 竞猜篮球
 * 
 * @ClassName: KjinfoBasketBallResult
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @date 2014年7月3日 下午3:29:37 a van 修改 (js 请求 换 接口)
 */
public class KjinfoBasketBallResult extends BaseActivity implements OnPullDownListener, OnItemClickListener {
	/** 上下文内容 */
	private Context context = null;
	private TextView timeText;
	private RelativeLayout btnSelTime;
	private LinearLayout btnSelWanfa;
	private List<Map<String, Object>> mData;

	/** 进度listview视图 */
	private ListView kjinfo_lv;
	/** 自定义下拉刷新组件 **/
	private PullDownView mPullDownView;
	/** 网络获取的数据 */
	private List<Map<String, Object>> netDataList;
	/** 请求第几页数据 */
	private int intPageNo = 1;// 0
	/** 是否有下一页 */
	private boolean nextPage = false;
	/** 是否按更多 */
	private boolean isPressMore = false;
	/** 开奖适配器 */
	private KjInfoListAdapter adapter;
	/** 记录总条数 */
	private int intTotalNum;
	// 显示页数
	private int pageSize = 10;

	private int selectIndexInDataIssue = 0;

	boolean isGetData = false;
	String[] issuesName;
	Button kjinfo_btn_totouzhu;

	private List<Map<String, Object>> issueData = null;

	private String issueid;

	/** 判断是否从推送通知过来 */
	private Boolean ifPush;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.context = this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.kjinfo_info_basketball);
		SysApplication.getInstance().addActivity(this);
		ifPush = getIntent().getBooleanExtra("ifPush", false);
		initView();
		titleBar();
		isGetData = false;
		btnSelTime.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if (isGetData) {// 只有已经从网络获取期次信息，才能选择期次
					Dialog dialog = null;
					Builder builder = new AlertDialog.Builder(KjinfoBasketBallResult.this);
					builder.setTitle(getString(R.string.kjinfo_match_selissue));
					// builder.setIcon(R.drawable.basketball);
					DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							if (which >= 0) {
								selectIndexInDataIssue = which;
								timeText.setText(issuesName[selectIndexInDataIssue]);
								issueid = issueData.get(selectIndexInDataIssue).get("IssueID").toString();
								dialog.dismiss();
								// 每次重新选择日期组件时需要从第一页开始查询
								intPageNo = 1;
								startMatchThread();
							}
						}
					};
					builder.setSingleChoiceItems(issuesName, selectIndexInDataIssue, onClickListener);
					dialog = builder.create();
					dialog.show();
				}
			}
		});

		initDateParma();

		kjinfo_btn_totouzhu.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(KjinfoBasketBallResult.this, JcBasketballActivity.class);
				startActivity(intent);
			}
		});

	}

	public void onResume() {
		super.onResume();
		
	}

	public void onPause() {
		super.onPause();
		
	}

	private void initView() {
		timeText = (TextView) findViewById(R.id.kjinfo_match_date);
		btnSelTime = (RelativeLayout) findViewById(R.id.kjinfo_match_seldate_rl);
		btnSelWanfa = (LinearLayout) findViewById(R.id.kjinfo_match_selwanfa_ll);
		btnSelWanfa.setVisibility(View.GONE);
		View kjinfo_match_selwanfa_lline = (View) findViewById(R.id.kjinfo_match_selwanfa_lline);
		kjinfo_match_selwanfa_lline.setVisibility(View.GONE);
		kjinfo_btn_totouzhu = (Button) findViewById(R.id.kjinfo_btn_totouzhu);
		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
		mPullDownView = (PullDownView) findViewById(R.id.kjinfo_lv);

		mPullDownView.setOnPullDownListener(this);

		kjinfo_lv = mPullDownView.getListView();

		kjinfo_lv.setOnItemClickListener(this);
	}

	/************************************** 2014年7月3日15:35:08 ************************************************/

	// 请求 时间 id 参数
	private void initDateParma() {
		AsyncLoaderDateInfo av = new AsyncLoaderDateInfo();
		String[] parms = new String[2];
		JSONObject params = new JSONObject();
		try {
			// 设置请求所需参数
			params.put("LottID", 91);
		} catch (JSONException ex) {
			Log.e("error", ex.toString());
		}
		parms[1] = params.toString();
		parms[0] = "313";
		av.execute(parms);
	}

	class AsyncLoaderDateInfo extends AsyncTask<String, integer, String> {
		ShowTipDialog dialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			dialog.showDialog(context);
		}

		@Override
		protected String doInBackground(String... params) {
			String strResult;
			String action = params[0];
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResults(params[1],UserID, action, getApplicationContext());
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			dialog.closeDialog();
			try {
				isGetData = true;
				JSONTokener jsonParser = new JSONTokener(result);
				JSONObject js = (JSONObject) jsonParser.nextValue();
				if (Integer.parseInt(js.getString("Code")) == 0) {
					String str = js.getString("Data");
					JSONObject js3 = new JSONObject(str);
					issueData = ConvertJsonToList.getList(js3.getString("item"));
					selectIndexInDataIssue = 0;
					timeText.setText(issueData.get(selectIndexInDataIssue).get("IssueName").toString());
					issueid = issueData.get(selectIndexInDataIssue).get("IssueID").toString();
					issuesName = new String[issueData.size()];
					for (int i = 0; i < issueData.size(); i++) {
						issuesName[i] = issueData.get(i).get("IssueName").toString().trim();
					}
					intPageNo = 1;
					selectIndexInDataIssue = 0;

					// 启动查询赛果线程
					startMatchThread();
				}
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	// 启动查询赛果线程
	private void startMatchThread() {
		// Log.d("vans", issueid+"------"+intPageNo);
		initData(issueid, intPageNo);
	}

	// 请求数据
	private void initData(String IssueID, int pageNO) {
		// Log.d("van", IssueID +"------------"+pageNO);
		AsyLoadFtInfo av = new AsyLoadFtInfo();
		String[] parms = new String[2];
		JSONObject params = new JSONObject();
		try {
			// 设置请求所需参数
			params.put("IssueID", IssueID);// "501224"
			params.put("PageNo", pageNO);
			params.put("PageSize", 10);
		} catch (JSONException ex) {
			Log.e("error", ex.toString());
		}
		parms[1] = params.toString();
		parms[0] = "311";
		av.execute(parms);
	}

	class AsyLoadFtInfo extends AsyncTask<String, Integer, String> {

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String strResult;
			String action = params[0];
			strResult = GetRequestParams.getRequestUserIDResult(params[1], ApplicationData.getInstance().getUserID(),
					action, getApplicationContext());
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			// Log.d("vans", result);
			try {
				JSONTokener jsonParser = new JSONTokener(result);
				JSONObject js = (JSONObject) jsonParser.nextValue();
				if (Integer.parseInt(js.getString("Code")) == 0) {
					String str = js.getString("Data");
					JSONObject js3 = new JSONObject(str);
					intTotalNum = Integer.valueOf(js3.getString("Count"));
					netDataList = ConvertJsonToList.getList(js3.getString("item"));
					// Log.d("tag", netDataList.toString());
				}

				if (intPageNo * pageSize >= intTotalNum) {
					nextPage = false;
				} else {
					nextPage = true;
				}
				showKList();

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	/**********************************************/

	/**
	 * 放入数据，显示listview视图
	 */
	public void showKList() {
		// 获取更多数据之外的请求，如首次请求数据，
		if (!isPressMore) {
			// 填充UI,listview
			// 获取胜负情况
			mData = modifymData(netDataList);
			if (mData != null) {
				// adapter = new SimpleAdapter(KjinfoBasketBallResult.this,
				// mData,
				// R.layout.kjinfo_info_match_lq_list, new String[] {
				// "MNo", "NMm", "HTeam", "Rq", "VTeam", "Score",
				// "Cg", "Dxf", "Sfc" }, new int[] {
				// R.id.kjinfo_match_list_mno,
				// R.id.kjinfo_match_list_mnm,
				// R.id.kjinfo_match_list_hteam,
				// R.id.kjinfo_match_list_rq,
				// R.id.kjinfo_match_list_vteam,
				// R.id.kjinfo_match_list_score,
				// R.id.kjinfo_match_list_cg,
				// R.id.kjinfo_match_list_dxf,
				// R.id.kjinfo_match_list_sfc });
				Log.e("KjinfoBasketBallResult", "showKList mData= " + mData.toString());
				adapter = new KjInfoListAdapter(KjinfoBasketBallResult.this, mData);
				kjinfo_lv.setAdapter(adapter);
			}
			// 隐藏并且禁用头部刷新
			mPullDownView.setHideHeader();
			// 显示并且可以使用头部刷新
			// mPullDownView.setShowHeader();
			/** 关闭 刷新完毕 ***/
			// mPullDownView.RefreshComplete();// 这个事线程安全的 可看源代码

		} else {
			// 获取更多数据
			List<Map<String, Object>> tData = new ArrayList<Map<String, Object>>();
			tData = modifymData(netDataList);
			mData.addAll(tData);
			adapter.notifyDataSetChanged();
		}
		// 判断是否有下一页
		if (nextPage) {
			// 显示并启用自动获取更多
			mPullDownView.setShowFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			mPullDownView.enableAutoFetchMore(true, 1);
		} else {
			// 隐藏 并禁用尾部
			mPullDownView.setHideFooter();
			// 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
			mPullDownView.enableAutoFetchMore(false, 1);
		}
		// 告诉它获取更多完毕 这个事线程安全的 可看源代码
		mPullDownView.notifyDidMore();

		isPressMore = false;

	}

	public List<Map<String, Object>> modifymData(List<Map<String, Object>> list) {
		if (list != null && list.size() != 0) {
			List<Map<String, Object>> NewList = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < list.size(); i++) {
				// {
				// "IssueNo": "131225305",
				// "Wk": "3",
				// "MName": "美国职业篮球联盟",
				// "HTeam": "金州勇士",
				// "VTeam": "洛杉矶快船",
				// "MTime": "2013/12/26 11:30:00",
				// "ETime": "2013/12/26 11:20:00",
				// "BgColor": "#006BBB",
				// "Rz": "103:105",
				// "RZResult": "2|-2.5,1,01,1|207.5"
				// }

				/*
				 * { "Wk": 7, "MNo": "140615301", "NMm": "美国女子篮球联盟", "ETime":
				 * "2014-06-18 00:50:00", "HTeam": "康涅狄格太阳", "VTeam": "纽约自由",
				 * "Score": "72:76", "Cg": "{ RZ:\"1|-2.5,1,01,2|150.5\",
				 * SP:\"1.6700,1.4800,11.5000,1.7400\", DG:\"3.98,0.0,3.7\" }" }
				 */

				Map<String, Object> OldMap = list.get(i);

				String json = OldMap.get("Cg").toString();
				String rzString = null;
				String spString = null;
				String dgString = null;
				try {
					JSONObject jsonObject = new JSONObject(json);
					rzString = jsonObject.getString("RZ");
					spString = jsonObject.getString("SP");
					dgString = jsonObject.getString("DG");
				} catch (JSONException e) {
					e.printStackTrace();
				}

				Map<String, Object> NewMap = new HashMap<String, Object>();
				String strCg;
				String Cg = "-";
				String rfsf = "-";
				String Dxf = "-";
				String Sfc = "-";
				// cg包含　　RZResult:
				// 2|-11.5,1,02,1|155.5，主负|让分，主胜，主胜6-10，大分|预设分155.5
				strCg = String.valueOf(rzString);
				if ("".equals(strCg) || strCg.split(",").length < 4) {
					Cg = "-";
					rfsf = "-";
					Dxf = "-";
					Sfc = "-";
				} else {
					// 胜负
					String Cg0 = strCg.split(",")[0].split("\\|")[0];
					if (Cg0.equals("1")) {
						Cg = "主胜";
					} else if (Cg0.equals("2")) {
						Cg = "主负";
					}
					// 让分胜负
					if (strCg.split(",")[0].split("\\|").length > 1) {
						rfsf = strCg.split(",")[0].split("\\|")[1];
					}

					// 大小分
					String Dxf0 = strCg.split(",")[3];
					if (Dxf0.split("\\|").length > 1) {
						if (Dxf0.split("\\|")[0].equals("1")) {
							Dxf = "大分(" + Dxf0.split("\\|")[1] + ")";
						} else if (Dxf0.split("\\|")[0].equals("2")) {
							Dxf = "小分(" + Dxf0.split("\\|")[1] + ")";
						}
					}
					// 胜分差
					String Sfc0 = strCg.split(",")[2];
					Sfc = KaiJiangUtil.dealJCLQSFC(Sfc0);
				}
				// //"MNo", "NMm", "HTeam", "Rq", "VTeam", "Score", "Cg", "Dxf",
				// "Sfc"
				// MNO服务器格式修改 130909001 改成周一001
				String MNo = OldMap.get("MNo").toString();
				MNo = DateUtil.getWeekName7(OldMap.get("Wk").toString())
						+ MNo.substring(MNo.length() - 3, MNo.length());
				NewMap.put("MNo", MNo);
				NewMap.put("NMm", OldMap.get("NMm"));
				NewMap.put("HTeam", OldMap.get("HTeam"));
				NewMap.put("Rq", rfsf);
				NewMap.put("VTeam", OldMap.get("VTeam"));
				String score = OldMap.get("Score").toString().replaceAll(":", "-");
				if (TextUtils.isEmpty(score)) {
					score = "-";
				}
				NewMap.put("Score", score);
				NewMap.put("Cg", Cg);
				NewMap.put("Dxf", Dxf);
				NewMap.put("Sfc", Sfc);
				NewList.add(NewMap);
			}
			return NewList;
		}
		return null;
	}

	/**
	 * listview单项点击事件
	 */
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// Toast.LENGTH_SHORT).show();
	}

	/**
	 * listview刷新
	 */
	public void onRefresh() {

	}

	/**
	 * listview更多
	 */
	public void onMore() {
		isPressMore = true;
		// 发送更多请求
		intPageNo++;
		startMatchThread();
	}

	class KjInfoListAdapter extends BaseAdapter {

		private LayoutInflater inflater = null;

		private List<Map<String, Object>> mData;

		public KjInfoListAdapter(Context context, List<Map<String, Object>> mData) {
			inflater = LayoutInflater.from(context);
			this.mData = mData;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			// int lotIdInt = Integer.parseInt(lottID);
			ViewHolder holder = null;
			holder = new ViewHolder();

			LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			layoutParams.gravity = Gravity.CENTER_VERTICAL;
			//
			// String redBTemp = mData.get(position).get("Ball").toString();
			// String blueBTemp =
			// mData.get(position).get("BlueBall").toString();

			convertView = inflater.inflate(R.layout.kjinfo_info_match_list, null);// kjinfo_info_match_lq_list
			holder.kjinfo_match_list_mno = (TextView) convertView.findViewById(R.id.kjinfo_match_list_mno);
			holder.kjinfo_match_list_mnm = (TextView) convertView.findViewById(R.id.kjinfo_match_list_mnm);
			holder.kjinfo_match_list_hteam = (TextView) convertView.findViewById(R.id.kjinfo_match_list_hteam);
			holder.kjinfo_match_list_rq = (TextView) convertView.findViewById(R.id.kjinfo_match_list_rq);
			holder.kjinfo_match_list_vteam = (TextView) convertView.findViewById(R.id.kjinfo_match_list_vteam);
			holder.kjinfo_match_list_score = (TextView) convertView.findViewById(R.id.kjinfo_match_list_score);
			holder.kjinfo_match_list_cg = (TextView) convertView.findViewById(R.id.kjinfo_match_list_cg);
			holder.kjinfo_match_list_mno.setText(mData.get(position).get("MNo").toString());
			holder.kjinfo_match_list_mnm.setText(mData.get(position).get("NMm").toString());
			// holder.kjinfo_match_list_hteam.setText(mData.get(position).get("HTeam").toString());
			// holder.kjinfo_match_list_rq.setText(mData.get(position).get("Rq").toString());
			holder.kjinfo_match_list_hteam.setText(mData.get(position).get("VTeam").toString());
			holder.kjinfo_match_list_vteam.setText(mData.get(position).get("HTeam").toString() + "("
					+ mData.get(position).get("Rq").toString() + ")");
			holder.kjinfo_match_list_score.setText(mData.get(position).get("Score").toString());
			if (mData.get(position).get("Cg").toString().equals("主胜")) {
				holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
						R.color.ui_txt_color_selected_red));
				// holder.kjinfo_match_list_score.setTextColor(context.getResources().getColor(R.color.kjinfo_detail_ftbg_qianhong));
			} else if (mData.get(position).get("Cg").toString().equals("平")) {
				holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
						R.color.ui_new_divider_bg));
				// holder.kjinfo_match_list_score.setTextColor(context.getResources().getColor(R.color.kjinfo_detail_ftbg_qianlan));
			} else if (mData.get(position).get("Cg").toString().equals("主负")) {
				holder.kjinfo_match_list_cg.setBackgroundColor(context.getResources().getColor(
						R.color.ui_new_btn_no_normal_solid));
				// holder.kjinfo_match_list_score.setTextColor(context.getResources().getColor(R.color.kjinfo_detail_ftbg_qianlv));
			}
			holder.kjinfo_match_list_cg.setText(mData.get(position).get("Cg").toString());

			convertView.setTag(holder);

			return convertView;
		}

		class ViewHolder {
			TextView kjinfo_match_list_mno;
			TextView kjinfo_match_list_mnm;
			TextView kjinfo_match_list_hteam; // 客队
			TextView kjinfo_match_list_rq;
			TextView kjinfo_match_list_vteam; // 主队
			TextView kjinfo_match_list_score;// 比分
			TextView kjinfo_match_list_cg;// 赛果
		}
	}

	// titleBar标题栏
	public void titleBar() {
		// Title信息(返回+Title)
		Button back = (Button) findViewById(R.id.top_title_back);
		// back.getBackground().setAlpha(255);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onKeyDown(KeyEvent.KEYCODE_BACK, null);

			}
		});

		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText(R.string.kjinfo_match_lq_result);

		Button refres = (Button) findViewById(R.id.top_title_refres);
		refres.getBackground().setAlpha(255);
		refres.setVisibility(View.INVISIBLE);
		refres.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// not event

			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if(ifPush){
				Intent intent = new Intent(this, JddMainActivity.class);
				startActivity(intent);
			}
			this.finish();
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}

	};

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();
		SysApplication.getInstance().removeActivity(this);
	};

}
